// #ifdef H5
import wxsdk from '@/wlkutils/wechat/sdk';
// #endif
import {router as $Router} from '@/wlkutils/router';
import store from '@/wlkutils/store';
import platform from '@/wlkutils/platform';


// 不同的支付方法
class PaymentMethod {
    constructor(paymentSelector) {
        this.paymentSelector = paymentSelector;
    }

    async prepay() {
        const params = {
            order_id: this.paymentSelector.order.id,
            payment: this.paymentSelector.payment,
            type: this.paymentSelector.type,
        };
        if (uni.getStorageSync('openid')) {
            params.openid = uni.getStorageSync('openid');
        }
        const res = await uni.$u.http.post('pay/prepay', params).catch((error) => {
            uni.$u.toast(`支付通道失败: ${error.message}`)
            return false
            // return Promise.reject(error);
        });
        if (!res) {
            return false
        }
        // http://localhost:8080/h5/#/pages/pay/pay?id=18&type=line
        return res.data;
    }

    async performPay() {
        throw new Error('not implemented');
    }

    async pay() {
        const prepayData = await this.prepay();

        if (prepayData) {
            await this.performPay(prepayData);

        }
    }
}

class WxOfficialAccountPay extends PaymentMethod {
    async performPay(prepayData) {
        const that = this.paymentSelector;
        const successCallback = (res) => {
            res.errMsg === 'chooseWXPay:ok' ? that.payResult('success') : that.payResult('fail');
        };
        wxsdk.map.wxpay(prepayData.result_payinfo, successCallback);
    }
}

class WxMiniProgramPay extends PaymentMethod {
    async performPay(prepayData) {
        const that = this.paymentSelector;
        uni.requestPayment({
            provider: 'wxpay',
            ...prepayData.result_payinfo,
            success: res => {
                that.payResult('success');
            },
            fail: err => {
                console.log('支付取消或者失败:', err);
                err.errMsg !== "requestPayment:fail cancel" && that.payResult('fail');
            }
        });
    }
}

class WechatWapPay extends PaymentMethod {
    async performPay(prepayData) {
        let url = prepayData.result_payinfo.match(/url\='(\S*)'/)[1].replace(/&amp;/g, '&');
        const {domain} = store.getters.initMain.content;
        const params = encodeURIComponent(`${domain}pages/order/payment/result?orderId=${this.paymentSelector.order.id}&type=${this.paymentSelector.payment}&orderType=${this.paymentSelector.orderType}`);
        window.location.href = `${url}&redirect_url=${params}`;
    }
}

class WalletPay extends PaymentMethod {
    async performPay() {
        // 直接支付成功
        this.paymentSelector.payResult('success');
    }
}

export default class PaymentSelector {
    constructor(payment, order, type) {
        this.payment = payment;
        this.order = order;
        this.type = type;
        this.platform = platform.get();
        this.paymentMethods = new Map()
            .set('wxOfficialAccount', new Map()
                .set('wechat', new WxOfficialAccountPay(this))
                .set('wallet', new WalletPay(this))
            )
            .set('wxMiniProgram', new Map()
                .set('wechat', new WxMiniProgramPay(this))
                .set('wallet', new WalletPay(this))
            )
            .set('H5', new Map()
                .set('wechat', new WechatWapPay(this))
                .set('wallet', new WalletPay(this))
            );

        this.selectPayment();
    }

    async selectPayment() {
        const paymentMethod = this.paymentMethods.get(this.platform).get(this.payment);
        await paymentMethod.pay();
    }

    payResult(status) {
        $Router.replace({
            path: '/pages/pay/result',
            query: {
                order_id: this.order.id,
                payment: this.payment,
                status: status,
                type: this.type,
            }
        });
    }
}
